package com.itheima.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.itheima.common.R;
import com.itheima.pojo.*;
import com.itheima.pojo.DTO.OrderDto;
import com.itheima.service.IOrderDetailService;
import com.itheima.service.IOrderService;
import com.itheima.utils.BaseContext;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    IOrderService orderService;

    @Autowired
    IOrderDetailService orderDetailService;

    //去支付，生成订单
    @PostMapping("/submit")
    private R<String> submit(@RequestBody Orders orders){
        orderService.submit(orders);
        return R.success("支付成功");
    }

    //分页查询订单
    @GetMapping("/userPage")
    private R<IPage> pageOrder(Integer page,Integer pageSize){

        IPage<Orders> Ipage = new Page<>(page,pageSize);
        //创建一个DishDTO对象，用来copy
        Page<OrderDto> orderDtoPage = new Page<>(page,pageSize);

        IPage<Orders> iPage = orderService.page(Ipage);
        //先查询Orders表
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,currentId);
        orderService.page(iPage,queryWrapper);

        //拷贝对象
        BeanUtils.copyProperties(Ipage,orderDtoPage,"records");

        List<Orders> records = Ipage.getRecords();
        //拷贝数据
        List<OrderDto> orderDtoList = records.stream().map((item) -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(item, orderDto);

            //查询是否有菜品
            Long orderId = item.getId();
            LambdaQueryWrapper<OrderDetail> w = new LambdaQueryWrapper<>();
            w.eq(OrderDetail::getOrderId, orderId);
            List<OrderDetail> list = orderDetailService.list(w);

            if (list != null) {
                orderDto.setOrderDetails(list);
            }
            return orderDto;
        }).collect(Collectors.toList());
        orderDtoPage.setRecords(orderDtoList);

        return R.success(orderDtoPage);
    }

    //订单明细
    @GetMapping("/page")
    private R<Page> page(Integer page,Integer pageSize,String number,
                         @JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8") String beginTime,
                         @JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8") String endTime)
    {
        Page queryPage =  orderService.page(page,pageSize,number,beginTime,endTime);
        return R.success(queryPage);
    }

    @GetMapping("/export")
    private void export(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("orders", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Orders.class).sheet("模板").doWrite(data());
    }
    private List data() {
        List<Orders> list = orderService.list();
        return list;
    }
}
